package com.xcity.game.rank.impl;

import java.util.Comparator;

import com.xcity.db.entity.Employee;
import com.xcity.db.entity.Player;
import com.xcity.db.entity.Ranking;
import com.xcity.game.combat.CombatUtils;
import com.xcity.game.event.GameEvents;
import com.xcity.game.formation.Formation;
import com.xcity.game.rank.BaseRankingList;

import naga.x.event.Event;

/**
 * 战斗力排行
 * @author yang.li
 *
 */
public class CombatPowerRankingList extends BaseRankingList {

	public CombatPowerRankingList(int type, int capacity, Comparator<Ranking> comparator) {
		super(type, capacity, comparator);
	}

	@Override
	public int[] getEventTypes() {
		return new int[] {
				GameEvents.EVENT_PLAYER_LOADED,
				GameEvents.EVENT_COMBAT_POWER_CHANGED,
				GameEvents.EVENT_EMPLOYEE_COMBAT_POWER_CHANGED,
				GameEvents.EVENT_FORMATION_CHANGED
				};
	}

	@Override
	public void handleEvent(Event event) {
		switch (event.getType()) {
			case GameEvents.EVENT_PLAYER_LOADED:
				playerLoaded(event.getParameter(0));
				break;
			case GameEvents.EVENT_COMBAT_POWER_CHANGED:
				fireCombatPowerChanged((Player) event.getParameter(0));
				break;
			case GameEvents.EVENT_EMPLOYEE_COMBAT_POWER_CHANGED:
				fireCombatPowerChanged((Employee) event.getParameter(0));
				break;
			case GameEvents.EVENT_FORMATION_CHANGED:
				fireCombatPowerChanged((Player) event.getParameter(0));
				break;
		}
	}
	
	protected void playerLoaded(Player player) {
		if (player.getCombatPower() > 0 && size() < getCapacity()) {
			fireCombatPowerChanged(player);
		}
	}
	
	protected void fireCombatPowerChanged(Player player) {
		int val = CombatUtils.getCombatPower(player, player.getFormations().get(Formation.TYPE_NORMAL).getUnits());
		if (val > 0) {
			setDirty(player, val);
		}
	}
	
	protected void fireCombatPowerChanged(Employee employee) {
		Player player = employee.getVm().getOwner();
		Formation f = player.getFormations().get(Formation.TYPE_NORMAL);
		if (f.contains(employee)) {
			// 普通阵型上的员工战斗力发生变化才更新
			fireCombatPowerChanged(player);
		}
	}

}
